
<template>
  <c-table-box ref="cTableBox" hide-func :checkbox="editable" :table-height="tableHeight" :data="comFileList" :table-config="tableConfig" @selection-change="selectionCHange">
    <template #btn>
      <CUpload
        v-show="fileList.length<limit&&editable"
        :id="id"
        ref="CUpload"
        v-model="fileList"
        :attachment-type="attachmentType"
        :belong-model="belongModel"
        :type-code="typeCode"
        :limit="limit"
        :model-id="modelId"
        v-bind="$attrs"
        :data="comData"
        @template-success="templateSuccessHandle"
      />
      <el-button v-if="editable" type="primary" style="margin-left:10px;" @click="removeHandle">删除附件</el-button>
    </template>
  </c-table-box>
</template>
<script>
import CUpload from './Upload'
import request from '@/utils/request'
import { otherFiltersItem } from '@/utils'
import { getShopAttachment, putShopAttachment } from '@/api/common'
export default {
  name: 'CFileTableBox',
  components: {
    CUpload
  },
  props: {
    limit: {// 文件上传限制个数
      type: Number,
      default: 200
    },
    value: {
      type: Array,
      default: () => []
    },
    editable: {
      type: Boolean,
      default: true
    },
    attachmentType: {
      type: String,
      default: ''
    }, // 附件类型
    belongModel: {
      type: String,
      default: ''
    }, // 所属模块
    id: {
      type: String,
      default: ''
    },
    typeCode: {
      type: String,
      default: ''
    },
    // 过滤配置查询参数
    // ==========
    filterAttachmentType: {
      type: String,
      default: ''
    }, // 附件类型
    filterBelongModel: {
      type: String,
      default: ''
    }, // 所属模块
    filterId: {
      type: String,
      default: ''
    },
    filterTypeCode: {
      type: String,
      default: ''
    },
    // ========
    modelId: {
      type: String,
      default: ''
    },
    tableHeight: {
      type: Number,
      default: 200
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      fileList: [],
      tableConfig: {
        interfacePath: '',
        setting: [
          {
            prop: 'attachmentUrl',
            label: '附件',
            render: (h, row) => {
              const v = this.getFileData(row)
              if (row.status === 'uploading') {
                // <el-progress type="circle" :percentage="100" status="success"></el-progress>
                const percentage = Math.floor(row.percentage)
                const progress = h('el-progress', {
                  props: {
                    type: 'circle',
                    percentage: percentage,
                    width: 40
                  }
                })
                return h('div', { class: 'attachment' }, [
                  progress,
                  h('div', { class: 'attachment-mask', on: { click: () => this.attachmentHandle(row) }}, [h('span', '终止')])
                ])
              }
              return h('c-accessory', { props: { src: v.attachmentUrl, type: v.typeName }})
            }
          },
          {
            prop: 'attachmentName',
            label: '附件名称',
            render: (h, row) => {
              const v = this.getFileData(row)
              if (this.editable && row.status === 'success') {
                return h('el-input', {
                  props: {
                    value: row.name,
                    placeholder: '请输入附件名称！'
                  },
                  on: {
                    input: v => {
                      this.$set(row, 'name', v)
                      this.$set(row.response.data, 'attachmentName', v)
                    },
                    change: v => {
                      if (v === '' || v === undefined) {
                        this.$message.warning('附件名称不能为空！')
                        // this.$set(row, 'name', v.attachmentName)
                      } else if (row.flag === 'data') {
                        // const name = row.response.data.attachmentName
                        this.$set(row.response.data, 'attachmentName', v.trim())
                        this.$set(row, 'name', v.trim())
                        // this.editAttachment(row).catch(() => {
                        // this.$set(row, 'name', name)
                        // })
                      } else {
                        this.$set(row.response.data, 'attachmentName', v)
                      }
                    }
                  }
                })
              }
              return h('span', v.attachmentName)
            }
          },
          {
            prop: 'typeName',
            label: '附件类型',
            render: (h, row) => {
              const v = this.getFileData(row)
              if (this.editable && row.status === 'success') {
                const filtersRaw = []
                if (this.attachmentType) {
                  const attachmentTypes = '[' + this.attachmentType + ']'
                  filtersRaw.push({ key: 'attachmentType', value: attachmentTypes, operator: 'in' })
                }
                if (this.belongModel) {
                  const modles = '[' + this.belongModel + ']'
                  filtersRaw.push({ key: 'belongModel', value: modles, operator: 'in' })
                }
                if (this.id) {
                  const ids = '[' + this.id + ']'
                  filtersRaw.push({ key: 'id', value: ids, operator: 'in' })
                }
                if (this.typeCode) {
                  const typeCodes = '[' + this.typeCode + ']'
                  filtersRaw.push({ key: 'typeCode', value: typeCodes, operator: 'in' })
                }
                return h('c-remote-select', {
                  props: {
                    url: '/api/v1/configAttachmentTemplate/page',
                    filtersRaw,
                    clearable: true,
                    filterable: true,
                    valueName: 'id',
                    labelName: 'attachmentType',
                    value: v.configAttachmentId,
                    pageFlag: false
                  },
                  attrs: {
                    placeholder: '请选择附件类型'
                  },
                  on: {
                    input: v => {
                      this.$set(row, 'configAttachmentId', v)
                      this.$set(row.response.data, 'configAttachmentId', v)
                    },
                    'update:label': v => {
                      this.$set(row.response.data, 'attachmentType', v)
                    },
                    change: v => {
                      if (row.flag === 'data') {
                        // this.editAttachment(row)
                      }
                    }
                  }
                })
              }
              return h('span', v.attachmentType)
            }
          },
          {
            prop: 'createBy',
            label: '上传人',
            formatData: row => {
              const v = this.getFileData(row)
              return v.createBy
            }
          },
          {
            prop: 'createTime',
            label: '上传时间',
            formatData: row => {
              const v = this.getFileData(row)
              return v.createTime
            }
          },
          {
            prop: '',
            label: '操作',
            render: (h, row) => {
              return h('el-button', {
                props: { type: 'text' },
                on: {
                  click: () => {
                    this.downAccessory(row)
                  }
                },
                nativeOn: {
                  click: e => {
                    e.stopPropagation()
                  }
                }
              }, '附件下载')
            }
          }
        ]
      },
      // fileListData: [],
      selections: [],
      rawFileListData: [],
      tempIds: []
    }
  },
  computed: {
    fileListData() {
      return this.rawFileListData.filter(e => {
        let isNone = this.attachmentType === '' && this.belongModel === '' && this.id === '' && this.typeCode === ''
        isNone = isNone && (this.filterAttachmentType === '' && this.filterBelongModel === '' && this.filterId === '' && this.filterTypeCode === '')
        return isNone || this.tempIds.includes(e.configAttachmentId) || e.configAttachmentId === '' || e.configAttachmentId === undefined
      })
    },
    comData() {
      return [...this.data, ...this.fileListData]
    },
    comFileList() {
      return this.fileList.filter(e => ((e.response || {}).data || {}).dr !== 1)
    }
  },
  watch: {
    fileList: {
      handler(v) {
        this.$emit('input', v)
      }
    },
    modelId: {
      handler(v) {
        this.getShopAttachment()
      },
      immediate: true
    }
  },
  created() {
    // this.getShopAttachment()
    this.getAttachmentType()
  },
  methods: {
    templateSuccessHandle(tempData) {
      if (this.modelId === '' || this.modelId === undefined) return
      const ids = tempData.map(e => e.id)
      this.tempIds.push(...ids)
      // const all = ids.length === 0
      // getShopAttachment(this.modelId).then(res => {
      //   this.fileListData = res.data.filter(e => {
      //     return all || ids.includes(e.configAttachmentId)
      //   })
      // })
    },
    // 根据modelId获取附件
    getShopAttachment() {
      if (this.modelId === '' || this.modelId === undefined) return
      getShopAttachment(this.modelId).then(res => {
        this.rawFileListData = res.data
      })
    },
    // 修改附件
    editAttachment(file) {
      return putShopAttachment(file.response.data).then(res => {
        this.$message.success('编辑保存成功！')
      })
    },
    getFileData(file) {
      return this.$refs.CUpload.getFileData(file)
    },
    downAccessory(row) {
      this.$refs.CUpload.downFile(row)
    },
    attachmentHandle(row) {
      this.$refs.CUpload.abort(row)
    },
    removeHandle(row) {
      if (!this.singleJudge(this.selections, '删除')) return
      this.$refs.CUpload.removeFile(this.selections)
      this.selections = []
    },
    selectionCHange(v) {
      this.selections = v
    },
    getAttachmentType() {
      if (this.filterAttachmentType === '' && this.filterBelongModel === '' && this.filterId === '' && this.filterTypeCode === '') {
        return
      }
      const data = new FormData()
      const filtersRaw = []
      if (this.filterAttachmentType) {
        filtersRaw.push(otherFiltersItem('attachmentType', `[${this.filterAttachmentType}]`, 'in'))
      }
      if (this.filterBelongModel) {
        filtersRaw.push(otherFiltersItem('belongModel', `[${this.filterBelongModel}]`, 'in'))
      }
      if (this.id) {
        filtersRaw.push(otherFiltersItem('id', `[${this.filterId}]`, 'in'))
      }
      if (this.filterTypeCode) {
        filtersRaw.push(otherFiltersItem('typeCode', `[${this.filterTypeCode}]`, 'in'))
      }
      data.append('filtersRaw', JSON.stringify(filtersRaw))
      data.append('pageFlag', false)
      request({
        url: '/api/v1/configAttachmentTemplate/page',
        method: 'POST',
        data
      }).then(res => {
        if (res.data.records.length === 0) {
          return
        }
        res.data.records.forEach(e => {
          this.tempIds.push(e.id)
        })
      })
    }
  }
}
</script>
<style lang="scss">
.attachment{
  position: relative;
  display: inline-block;
  &:hover .attachment-mask{
    display: inline-block;
  }
  .attachment-mask{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    cursor: pointer;
    background-color: rgba(3,3,3,0.6);
    span{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      color: #fff;
    }
  }
}
</style>
